package cn.mymall.service.impl;

import cn.mymall.entity.Member;
import cn.mymall.help.PageHepler;
import cn.mymall.help.PageVo;
import cn.mymall.mapper.MemberMapper;
import cn.mymall.service.IMemberService;
import cn.mymall.util.BeanUtil;
import cn.mymall.util.RandomUtil;
import cn.mymall.vo.member.MemberReqVo;
import cn.mymall.vo.member.MemberResVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author liqilun
 * @since 2022-10-22
 */
@Service
public class MemberServiceImpl extends BaseServiceImpl<MemberMapper, Member> implements IMemberService {
    @Override
    public PageVo queryPage(MemberReqVo reqVo) {
        QueryWrapper query = new QueryWrapper<>();
        if (StringUtils.isNotBlank(reqVo.getMobile())) {
            query.eq("mobile", reqVo.getMobile());
        }
        if (reqVo.getInviter()!=null) {
            query.eq("inviter", reqVo.getInviter());
        }
        if(StringUtils.isNotBlank(reqVo.getInviterMobile())){
            Member member = getMemberByMobile(reqVo.getInviterMobile());
            if (member != null) {
                query.eq("inviter", member.getId());
            }
        }
        query.orderByDesc("id");
        Page page = page(new Page(reqVo.getPageNo(), reqVo.getPageSize()), query);
        List<Member> memberList = page.getRecords();
        List<MemberResVo> resVoList = new ArrayList<>();
        for (Member member : memberList) {
            MemberResVo resVo = new MemberResVo();
            BeanUtil.copyProperties(resVo, member);
            resVoList.add(resVo);
        }
        return PageHepler.convertPageVo(page, resVoList);
    }

    @Override
    public Member getMemberByMobile(String mobile) {
        return getOne(new QueryWrapper<Member>().eq("mobile", mobile));
    }

    @Override
    public Member getMemberByOpenid(String openid) {
        return getOne(new QueryWrapper<Member>().eq("openid", openid));
    }
    @Override
    public String getMemberAuthCode(Member member) {
        String auth_code = RandomUtil.getRandomString(64).toUpperCase();
        redisHelper.set(auth_code, member.getId());
        return auth_code;
    }

    @Override
    public Member getMemberByAuthCode(String auth_code) {
        Integer memberId = (Integer) redisHelper.get(auth_code);
        if(memberId!=null){
            return getById(memberId);
        }
        return null;
    }
}
